'use strict';

const Controller = require('egg').Controller;

class LocationController extends Controller {

  /**
   * 获取当前位置
   * GET /api/v1/location/current
   */
  async getCurrentLocation() {
    const { ctx } = this;
    
    try {
      // 获取客户端IP
      const ip = ctx.request.ip || ctx.ip;
      
      // 从请求参数获取位置信息
      const { lat, lng, address } = ctx.query;
      
      const location = await ctx.service.location.getCurrentLocation({
        ip,
        lat: lat ? parseFloat(lat) : null,
        lng: lng ? parseFloat(lng) : null,
        address
      });
      
      ctx.body = {
        code: 200,
        message: '获取位置成功',
        data: location
      };
      
    } catch (error) {
      console.error('获取当前位置失败:', error);
      ctx.body = {
        code: 500,
        message: '获取位置失败',
        data: null
      };
    }
  }

  /**
   * 地理编码（地址转坐标）
   * POST /api/v1/location/geocode
   */
  async geocode() {
    const { ctx } = this;
    
    try {
      const { address } = ctx.request.body;
      
      if (!address) {
        ctx.body = {
          code: 400,
          message: '地址不能为空',
          data: null
        };
        return;
      }
      
      const location = await ctx.service.location.geocode(address);
      
      ctx.body = {
        code: 200,
        message: '地理编码成功',
        data: location
      };
      
    } catch (error) {
      console.error('地理编码失败:', error);
      ctx.body = {
        code: 500,
        message: '地理编码失败',
        data: null
      };
    }
  }

  /**
   * 逆地理编码（坐标转地址）
   * POST /api/v1/location/reverse
   */
  async reverseGeocode() {
    const { ctx } = this;
    
    try {
      const { lat, lng } = ctx.request.body;
      
      if (!lat || !lng) {
        ctx.body = {
          code: 400,
          message: '经纬度不能为空',
          data: null
        };
        return;
      }
      
      const location = await ctx.service.location.reverseGeocode(
        parseFloat(lat), 
        parseFloat(lng)
      );
      
      ctx.body = {
        code: 200,
        message: '逆地理编码成功',
        data: location
      };
      
    } catch (error) {
      console.error('逆地理编码失败:', error);
      ctx.body = {
        code: 500,
        message: '逆地理编码失败',
        data: null
      };
    }
  }

  /**
   * 获取城市列表
   * GET /api/v1/location/cities
   */
  async getCities() {
    const { ctx } = this;
    
    try {
      const cities = ctx.service.location.getCityList();
      
      ctx.body = {
        code: 200,
        message: '获取城市列表成功',
        data: cities
      };
      
    } catch (error) {
      console.error('获取城市列表失败:', error);
      ctx.body = {
        code: 500,
        message: '获取城市列表失败',
        data: []
      };
    }
  }

  /**
   * 根据IP获取位置
   * GET /api/v1/location/ip
   */
  async getLocationByIP() {
    const { ctx } = this;

    try {
      const { ip } = ctx.query;
      let clientIP = ip || this.getRealClientIP(ctx);

      console.log('🔍 获取到的IP地址:', clientIP);

      const location = await ctx.service.location.getLocationByIP(clientIP);

      ctx.body = {
        code: 200,
        message: 'IP定位成功',
        data: {
          ...location,
          ip: clientIP
        }
      };

    } catch (error) {
      console.error('IP定位失败:', error);
      ctx.body = {
        code: 500,
        message: 'IP定位失败',
        data: null
      };
    }
  }

  /**
   * 获取真实的客户端IP地址
   * @param {Object} ctx - Koa上下文
   * @returns {string} IP地址
   */
  getRealClientIP(ctx) {
    // 尝试从各种头部获取真实IP
    const headers = [
      'x-forwarded-for',
      'x-real-ip',
      'x-client-ip',
      'cf-connecting-ip', // Cloudflare
      'x-cluster-client-ip',
      'forwarded'
    ];

    for (const header of headers) {
      const value = ctx.request.headers[header];
      if (value) {
        // x-forwarded-for 可能包含多个IP，取第一个
        const ip = value.split(',')[0].trim();
        if (ip && !this.isLocalIP(ip)) {
          return ip;
        }
      }
    }

    // 回退到默认IP
    return ctx.request.ip || ctx.ip || '127.0.0.1';
  }

  /**
   * 检查是否为本地IP
   * @param {string} ip - IP地址
   * @returns {boolean} 是否为本地IP
   */
  isLocalIP(ip) {
    if (!ip) return true;

    const localIPs = ['127.0.0.1', 'localhost', '::1', '0.0.0.0'];
    if (localIPs.includes(ip)) return true;

    const privateRanges = [
      /^10\./,
      /^172\.(1[6-9]|2[0-9]|3[0-1])\./,
      /^192\.168\./,
      /^169\.254\./
    ];

    return privateRanges.some(range => range.test(ip));
  }

  /**
   * 搜索地点
   * GET /api/v1/location/search
   */
  async searchLocation() {
    const { ctx } = this;
    
    try {
      const { keyword, city } = ctx.query;
      
      if (!keyword) {
        ctx.body = {
          code: 400,
          message: '搜索关键词不能为空',
          data: []
        };
        return;
      }
      
      // 这里可以调用地图API的POI搜索功能
      // 暂时返回模拟数据
      const results = [
        {
          name: keyword,
          address: `${city || '北京'}${keyword}`,
          latitude: 39.9042,
          longitude: 116.4074,
          city: city || '北京'
        }
      ];
      
      ctx.body = {
        code: 200,
        message: '搜索成功',
        data: results
      };
      
    } catch (error) {
      console.error('搜索地点失败:', error);
      ctx.body = {
        code: 500,
        message: '搜索失败',
        data: []
      };
    }
  }
}

module.exports = LocationController;
